package com.siyoumi.sh.modules.common.send_msg;

import com.siyoumi.util.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

//钉钉发信息
public class DingTalkSendMsg
        implements ISendMsg {
    @Override
    public XReturn send(String msg, String title) {
        Map<String, Object> post_data = new HashMap<String, Object>();
        post_data.put("msgtype", "markdown");
        //内容
        Map<String, Object> markdown = new HashMap<String, Object>();
        markdown.put("title", title);
        markdown.put("text", msg);
        post_data.put("markdown", markdown);
        //是否@所有人
        Map<String, Object> at = new HashMap<String, Object>();
        at.put("isAtAll", true);
        post_data.put("at", at);

        return sendApi(post_data);
    }

    protected String getAccessToken() {
        return System.getenv("DINGTALK_TOKEN");
    }

    protected String getSecret() {
        return System.getenv("DINGTALK_SECRET");
    }

    /**
     * 调用接口
     *
     * @param post_data post参数
     * @return 请求结果
     */
    private XReturn sendApi(Map<String, Object> post_data) {
        Long timestamp = XDate.toMs();
        String sign = getSign(timestamp);

        Map<String, String> data = new HashMap<String, String>();
        data.put("timestamp", timestamp.toString());
        data.put("sign", sign);
        String query = XStr.queryFromMap(data, null, false);

        XReturn r;
        try {
            String url = XStr.concat(this.getAccessToken(), "&", query);
            XLog.info(this.getClass(), "url:", url);
            XLog.info(this.getClass(), post_data);

            XHttpClient client = XHttpClient.getInstance();
            String returnStr = client.postJson(url, null, post_data);
            XLog.info(this.getClass(), returnStr);
            r = XJson.parseObject(returnStr, XReturn.class);
        } catch (Exception ex) {
            XLog.error(this.getClass(), ex.getMessage());
            r = XReturn.getR(123456, ex.getMessage());
        }

        return r;
    }


    /**
     * 生成签名
     *
     * @param timestamp 时间
     * @return 签名
     */
    private String getSign(Long timestamp) {
        String sign = "";
        try {
            String string1 = timestamp + "\n" + this.getSecret();
            byte[] sign_hmac = XStr.hmacSHA256(string1, this.getSecret());
            sign = URLEncoder.encode(XStr.base64Enc(sign_hmac), StandardCharsets.UTF_8);

            XLog.debug(this.getClass(), string1);
            XLog.debug(this.getClass(), sign_hmac);
            XLog.debug(this.getClass(), sign);
        } catch (Exception ex) {
            XLog.error(this.getClass(), ex.getMessage());
        }

        return sign;
    }
}
